﻿using Microsoft.EntityFrameworkCore;

using SRM.Application.PageResult.Dtos;
using SRM.Application.PageResult.IServices;
using SRM.Core.Models;
using SRM.Core.Models.Base;
using SRM.Core.Repositories;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SRM.Application.PageResult.DeliverOrderPage
{
    public class DeliverOrderServer : IDeliverOrderServer
    {
        private readonly IRepository<DeliverOrder> _reliverOrderRepository;

        public DeliverOrderServer(IRepository<DeliverOrder> reliverOrderRepository)
        {
            _reliverOrderRepository = reliverOrderRepository;
        }

        public async Task<PagerModel<DeliverOrder>> GetDeliverOrderList(PagerModelInput input)
        {
            var query = _reliverOrderRepository.GetAll()
                .Include(d => d.PurchaseOrder)
                .Include(d => d.ReturnOrder)
                .AsNoTracking();

            if (!string.IsNullOrEmpty(input.FilterText))
            {
                query = query.Where(s => s.DeliverOrderNo.Contains(input.FilterText));
            }

            if (!LoginUser.LoginUsers.IsHQ)
            {
                query = query.Where(q => q.SupplierId == LoginUser.LoginUsers.SupplierId);
            }

            query = query.Where(q =>
            q.ReturnOrder.ReviewState == Core.Extension.ReturnOrderStateEnum.已复审);
            var data = await query.ToListAsync();

            data.Sort((DeliverOrder d1, DeliverOrder d2) => d2.CreateDate.CompareTo(d1.CreateDate));

            PagerModel<DeliverOrder> pagerModel = PagedList<DeliverOrder>.PageList(input, data);
            return pagerModel;
        }
    }
}
